package cn.edu.cdtu.healthclient.activity;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import android.app.Activity;
import android.app.Service;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import cn.edu.cdtu.healthclient.activity.util.SystemUiHider;
import cn.edu.cdtu.healthclient.domain.Test;
import cn.edu.cdtu.healthclient.domain.TestType;
import cn.edu.cdtu.healthclient.service.HealthService;
import cn.edu.cdtu.healthclient.service.HealthService.HealthBinder;
import cn.edu.cdtu.healthclient.task.ActivityTaskQueue;
import cn.edu.cdtu.healthclient.utils.ConnectUtil.HealthServerContect;
import cn.edu.cdtu.healthclient.utils.ConnectUtil.HealthTestPargrams;
import cn.edu.scu.healthclient.activity.R;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

/**
 * An example full-screen activity that shows and hides the system UI (i.e.
 * status bar and navigation/system bar) with user interaction.
 *
 * @see SystemUiHider
 */
public class TestActivity extends Activity {
	
	/*
	 * 
	 */
	private ActivityTaskQueue taskQueue;
	public ActivityTaskQueue getTaskQueue(){
		return taskQueue;
	}
	/*
	 * 
	 */
	private HealthBinder binder;
	public HealthBinder getBinder(){
		return binder;
	}
	/*
	 * 
	 */
	private ServiceConnection serviceConnection = new ServiceConnection() {
		
		@Override
		public void onServiceDisconnected(ComponentName name) {
			// TODO Auto-generated method stub
			binder = null;
			taskQueue.shutdownTaskQueue();
		}
		
		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
			// TODO Auto-generated method stub
			binder = (HealthBinder)service;
			if(!taskQueue.isRunning()){
				taskQueue.start();
			}
		}
	};
	
	/*
	 * 
	 */
	private final Intent serviceIntent = new Intent(HealthService.ACTION);
	
	private ListView listView;
	private TextView topTitle;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		startService(serviceIntent);
    	taskQueue = new ActivityTaskQueue();
//    	this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
//				WindowManager.LayoutParams.FLAG_FULLSCREEN);  
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_test);
		listView = (ListView) findViewById(R.id.health_test_list);
		topTitle = (TextView) findViewById(R.id.topTitle);  
	    topTitle.setText("试题列表");
	}

	/* (non-Javadoc)
	 * <p>Title: onStart</p> 
	 * <p>Description: </p>  
	 * @see android.app.Activity#onStart()
	 */
	@Override
	protected void onStart() {
		// TODO Auto-generated method stub
		bindService(serviceIntent, 
        		serviceConnection, Service.BIND_AUTO_CREATE);
		super.onStart();
		taskQueue.addTask(new Thread(new TestTaskImplementation()));
	}

	/* (non-Javadoc)
	 * <p>Title: onStop</p> 
	 * <p>Description: </p>  
	 * @see android.app.Activity#onStop()
	 */
	@Override
	protected void onStop() {
		// TODO Auto-generated method stub
		super.onStop();
		unbindService(serviceConnection);
	}
	/**
	 * 
	 * @ClassName: TestTaskImplementation 
	 * @Description: TODO
	 * @author 
	 * @date 
	 *
	 */
	private class TestTaskImplementation implements Runnable{

		/* (non-Javadoc)
		 * <p>Title: run</p> 
		 * <p>Description: </p>  
		 * @see java.lang.Runnable#run()
		 */
		@Override
		public void run() {
			// TODO Auto-generated method stub
			Gson gson = new Gson();
			HttpClient httpClient = binder.getHttpClient();
			HttpPost httpPost = new HttpPost(HealthServerContect.SERVER_URL
					+ HealthServerContect.TEST_SERVLET);
			List<NameValuePair> postParams = new ArrayList<NameValuePair>();
			postParams.add(new BasicNameValuePair(
					HealthTestPargrams.Option.HEALTH_TEST_OPTION,
					HealthTestPargrams.Option.OptionValue.HEALTH_TEST_OPTION_GET_TEST));
			//Log.i("DEBUG_TAG:", "开始取出参数");
			Intent intent = getIntent();
			TestType testType = (TestType) intent.getSerializableExtra(
					HealthTestPargrams.Pargram.SELECT_TEST_TYPE);
			postParams.add(new BasicNameValuePair(
					HealthTestPargrams.Pargram.SELECT_TEST_TYPE, 
					gson.toJson(testType)));
			//Log.i("DEBUG_TAG:", gson.toJson(testType));
			try {
				httpPost.setEntity(new UrlEncodedFormEntity(postParams,"utf-8"));
				HttpResponse response = httpClient.execute(httpPost);
				if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
					String message = EntityUtils.toString(response.getEntity());
					//Log.i("DEBUG_TAG:", message);
					final List<Test> tests = gson.fromJson(message, 
							new TypeToken<List<Test>>(){}.getType());
					runOnUiThread(new Runnable() {
						
						@Override
						public void run() {
							// TODO Auto-generated method stub
							listView.setAdapter(new TestAdapter(tests));
						}
					});
				}
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (ClientProtocolException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
	}
	
	/**
	 * 
	 * @ClassName: TestAdapter 
	 * @Description: TODO
	 * @author 
	 * @date 
	 *
	 */
	private class TestAdapter extends BaseAdapter{

		private Test[] tests;
		
		/** 
		 * @Title: FragmentSearch.TestAdapter
		 * @Description: TODO
		 * @throws 
		 *
		 */
		public TestAdapter(List<Test> testList) {
			// TODO Auto-generated constructor stub
			tests = testList.toArray(new Test[testList.size()]);
		}
		
		/* (non-Javadoc)
		 * <p>Title: getCount</p> 
		 * <p>Description: </p> 
		 * @return 
		 * @see android.widget.Adapter#getCount()
		 */
		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return tests.length;
		}

		/* (non-Javadoc)
		 * <p>Title: getItem</p> 
		 * <p>Description: </p> 
		 * @param position
		 * @return 
		 * @see android.widget.Adapter#getItem(int)
		 */
		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return null;
		}

		/* (non-Javadoc)
		 * <p>Title: getItemId</p> 
		 * <p>Description: </p> 
		 * @param position
		 * @return 
		 * @see android.widget.Adapter#getItemId(int)
		 */
		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return position;
		}
		
		/**
		 * 
		 * @ClassName: ViewHolder 
		 * @Description: Adapter的View Holder机制用到的Holder
		 * @author 
		 * @date 
		 *
		 */
		private final class ViewHolder{
			TextView testName;
			TextView testDescription;
			Button seeTest;
			Button logTest;
		}
		/* (non-Javadoc)
		 * <p>Title: getView</p> 
		 * <p>Description: </p> 
		 * @param position
		 * @param convertView
		 * @param parent
		 * @return 
		 * @see android.widget.Adapter#getView(int, android.view.View, android.view.ViewGroup)
		 */
		@Override
		public View getView(final int position, View convertView, ViewGroup parent) {
			// TODO Auto-generated method stub
			ViewHolder viewHolder = null;
			if(convertView == null){
				viewHolder = new ViewHolder();
				convertView = (LayoutInflater.from(TestActivity.this)).inflate(
						R.layout.activity_test_adapter_test,
						parent,false);
				viewHolder.testName = (TextView)convertView.findViewById(R.id.test_name);
				viewHolder.testDescription = 
						(TextView)convertView.findViewById(R.id.test_descrption);
				viewHolder.seeTest = (Button) convertView.findViewById(
						R.id.get_question_by_test);
				viewHolder.logTest = (Button) convertView.findViewById(
						R.id.get_test_log);
				convertView.setTag(viewHolder);
			}else{
				viewHolder = (ViewHolder)convertView.getTag();
			}
			viewHolder.testName.setText(tests[position].getTest());
			viewHolder.testDescription.setText(tests[position].getDescription());
			//final String tempName = (String) viewHolder.testName.getText();
			viewHolder.seeTest.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					Bundle bundle = new Bundle();
					bundle.putSerializable(
							HealthTestPargrams.Pargram.SELECT_TEST
							, tests[position]);
					Intent intent = new Intent(TestActivity.this,QuestionActivity.class);
					intent.putExtras(bundle);
					startActivity(intent);
				}
			});
			viewHolder.logTest.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					Bundle bundle = new Bundle();
					bundle.putSerializable(
							HealthTestPargrams.Pargram.SELECT_TEST
							, tests[position]);
					Intent intent = new Intent(TestActivity.this,TestLogActivity.class);
					intent.putExtras(bundle);
					startActivity(intent);
				}
			});
			return convertView;
		}
	}
}
